package com.xie.smfs.entity;

import com.xie.smfs.registry.ModEntities;
import net.minecraft.entity.ai.goal.ActiveTargetGoal;
import net.minecraft.entity.data.TrackedDataHandlerRegistry;
// 不要删除这条注释，该注释介绍本模块功能
// 这里定义了一个新的生物种类，和原版的亡灵生物类相似
// 属于这个类的生物都有如下代码定义的特性
import com.xie.smfs.registry.ModEffects;
import com.xie.smfs.damage.ModDamageSources;

import net.minecraft.entity.EntityType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageType;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.entity.mob.PathAwareEntity;
import net.minecraft.entity.vehicle.BoatEntity;
import net.minecraft.entity.vehicle.AbstractMinecartEntity;
import net.minecraft.entity.ai.goal.MeleeAttackGoal;
import net.minecraft.entity.ai.goal.WanderAroundFarGoal;
import net.minecraft.entity.attribute.DefaultAttributeContainer;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.DamageTypes;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.world.World;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.ActionResult;
import java.util.Random;
import java.util.Collections;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Hand;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.util.Arm;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.entity.data.DataTracker;
import net.minecraft.entity.data.TrackedData;
import net.minecraft.entity.data.TrackedDataHandlerRegistry;
import com.xie.smfs.registry.LostStatusEffectInstance;
import com.xie.smfs.item.RedGhostCandleItem;
import com.xie.smfs.item.WhiteGhostCandleItem;
import com.xie.smfs.registry.ModItems;
import net.minecraft.entity.effect.StatusEffects;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xie.smfs.manager.GhostDomainManager;

public class GhostEntity extends PathAwareEntity {
    @Override
    public boolean canImmediatelyDespawn(double distanceSquared) {
        return false; // 防止自然消失
    }

    private boolean isSuppressed = false;
    private final boolean isDeadlocked = false;
    boolean movementDisabled = false;
    private ItemStack coffinNail = ItemStack.EMPTY;
    boolean ghostDomainEnabled = true;
    int attackCooldown;
    int ghostLevel; // 添加鬼等级字段
    private LivingEntity attackTarget; // 攻击冷却时间
    private boolean killingRulesEnabled = true;
    private boolean isVisible = true; // 可见性标志（默认可见）
    private int visibleTicks = 0; // 可见计时器

    protected boolean isKillingRulesEnabled() {
        return killingRulesEnabled;
    }

    protected void setKillingRulesEnabled(boolean enabled) {
        this.killingRulesEnabled = enabled;
    }

    protected static final Logger LOGGER = LoggerFactory.getLogger(GhostEntity.class);
    private static final TrackedData<Boolean> DEADLOCKED = DataTracker.registerData(GhostEntity.class, TrackedDataHandlerRegistry.BOOLEAN);
    private static final TrackedData<Float> GHOST_DOMAIN_RADIUS = DataTracker.registerData(GhostEntity.class, TrackedDataHandlerRegistry.FLOAT);
    private static final TrackedData<Integer> SPIRITUAL_STRENGTH = DataTracker.registerData(GhostEntity.class, TrackedDataHandlerRegistry.INTEGER);
    private static final TrackedData<Integer> SPIRITUAL_RESISTANCE = DataTracker.registerData(GhostEntity.class, TrackedDataHandlerRegistry.INTEGER);
    private static final TrackedData<Integer> SPIRITUAL_DAMAGE = DataTracker.registerData(GhostEntity.class, TrackedDataHandlerRegistry.INTEGER);
    private static final TrackedData<Float> RECOVERY_FACTOR = DataTracker.registerData(GhostEntity.class, TrackedDataHandlerRegistry.FLOAT);
    private static final int MIN_STRENGTH_FOR_DEADLOCK = 400;
    private static final int MAX_SPIRITUAL_STRENGTH = 1000;

    // 压制状态相关方法
    public boolean isSuppressed() {
        return isSuppressed;
    }

    public boolean isDeadlocked() {
        return this.dataTracker.get(DEADLOCKED);
    }

    public void setSuppressed(boolean suppressed) {
        isSuppressed = suppressed;
        this.dataTracker.set(DEADLOCKED, suppressed);
        if (suppressed) {
            clearGhostDomainEffects();
        }
    }

    // Visibility control methods
    public boolean getVisible() {
        return isVisible;
    }

    public void setVisible(boolean visible) {
        this.isVisible = visible;
    }

    public int getVisibleTicks() {
        return visibleTicks;
    }

    public void setVisibleTicks(int ticks) {
        this.visibleTicks = ticks;
    }

    public void setMovementDisabled(boolean disabled) {
        this.movementDisabled = disabled;
        if (disabled) {
            this.setVelocity(Vec3d.ZERO);
        }
    }

    public void setDeadlocked(boolean deadlocked) {
        this.dataTracker.set(DEADLOCKED, deadlocked);
        if (deadlocked) {
            clearGhostDomainEffects();
        }
    }

    @Override
    public boolean isCollidable() {
        // 被压制或死机时不可碰撞
        if (isSuppressed() || isDeadlocked() || movementDisabled) {
            return false;
        }
        return super.isCollidable();
    }

    @Override
    public boolean isPushable() {
        // 免疫来自船和矿车的推动
        if (!getWorld().getEntitiesByClass(BoatEntity.class, getBoundingBox().expand(0.5), Entity::isAlive).isEmpty() ||
                !getWorld().getEntitiesByClass(AbstractMinecartEntity.class, getBoundingBox().expand(0.5), Entity::isAlive).isEmpty()) {
            return false;
        }
        return super.isPushable();
    }

    @Override
    public void pushAwayFrom(Entity entity) {
        // 免疫来自船和矿车的推动
        if (entity instanceof BoatEntity || entity instanceof AbstractMinecartEntity) {
            return;
        }
        super.pushAwayFrom(entity);
    }

    public boolean hasCoffinNail() {
        return coffinNail != null && !coffinNail.isEmpty();
    }

    public ItemStack getCoffinNail() {
        return coffinNail;
    }

    public void setCoffinNail(ItemStack nail) {
        this.coffinNail = nail;
    }

    public void disableGhostDomain() {
        this.ghostDomainEnabled = false;
        // 禁用鬼域的具体实现
        double previousRadius = getGhostDomainRadius();
        this.hasGhostDomain = false;
        setGhostDomainRadius(0);
        clearGhostDomainEffects(previousRadius);
    }

    private void clearGhostDomainEffects(double radius) {
        Vec3d center = this.getPos();
        for (PlayerEntity player : getWorld().getPlayers()) {
            if (player.squaredDistanceTo(center) <= radius * radius) {
                player.removeStatusEffect(ModEffects.LOST);
            }
        }
    }

    public void enableGhostDomain() {
        this.ghostDomainEnabled = true;
        // 启用鬼域的具体实现
        this.hasGhostDomain = true;
        setGhostDomainRadius(getDefaultGhostDomainRadius());
    }

    public void disableKillingRules() {
        this.killingRulesEnabled = false;
        // 禁用杀人规则的具体实现
        this.attackCooldown = 0;
        this.attackTarget = null;
    }

    public void enableKillingRules() {
        this.killingRulesEnabled = true;
        // 启用杀人规则的具体实现
        this.attackCooldown = getDefaultAttackCooldown();
    }

    // 清除鬼域效果
    private void clearGhostDomainEffects() {
        // 移除鬼域对玩家的所有效果
        for (PlayerEntity player : getWorld().getPlayers()) {
            if (isInGhostDomain(player)) {
                player.removeStatusEffect(ModEffects.LOST);
                player.removeStatusEffect(StatusEffects.BLINDNESS);
                player.removeStatusEffect(StatusEffects.SLOWNESS);
            }
        }
    }

    // 获取默认鬼域半径
    protected float getDefaultGhostDomainRadius() {
        return 10.0f + (this.ghostLevel * 2.0f);
    }

    // 检查玩家是否在鬼域内
    private boolean isInGhostDomain(PlayerEntity player) {
        return this.squaredDistanceTo(player) <= (getGhostDomainRadius() * getGhostDomainRadius());
    }

    // 获取默认攻击冷却时间
    private int getDefaultAttackCooldown() {
        return 20; // 默认20 ticks (1秒)
    }

    public static DefaultAttributeContainer.Builder createGhostAttributes() {
        return LivingEntity.createLivingAttributes()
                .add(EntityAttributes.GENERIC_MAX_HEALTH, 20.0)
                .add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 0.25)
                .add(EntityAttributes.GENERIC_ATTACK_DAMAGE, 5.0)
                .add(EntityAttributes.GENERIC_ATTACK_KNOCKBACK, 0.0)
                .add(EntityAttributes.GENERIC_FOLLOW_RANGE, 16.0);
    }

    // 特性标志位
    public static boolean ENABLE_INVULNERABLE = true;
    public static boolean ENABLE_BLACK_PARTICLES = true;
    private final Random random = new Random();

    protected boolean isHasGhostDomain() {
        return hasGhostDomain;
    }
    private boolean hasGhostDomain;
    private final int ghostDomainLevel;
    // 使用DataTracker同步鬼域半径
    private final char terrorLevel; // 恐怖等级: S, A, B, C

    protected void applyDefaultEffects(PlayerEntity player) {
        // 默认添加失明效果
        player.addStatusEffect(new StatusEffectInstance(StatusEffects.BLINDNESS, 200, 0, false, false));
    }

    public GhostEntity(EntityType<? extends GhostEntity> entityType, World world) {
        this(entityType, world, false, 0, 5.0f, 'C');
    }

    public GhostEntity(EntityType<? extends GhostEntity> entityType, World world, boolean hasGhostDomain, int ghostDomainLevel, double ghostDomainRadius) {
        this(entityType, world, hasGhostDomain, ghostDomainLevel, ghostDomainRadius, 'C');
    }

    public GhostEntity(EntityType<? extends GhostEntity> entityType, World world, boolean hasGhostDomain, int ghostDomainLevel, double ghostDomainRadius, char terrorLevel) {
        super(entityType, world);
        this.hasGhostDomain = hasGhostDomain;
        this.ghostDomainLevel = ghostDomainLevel;
        this.dataTracker.set(GHOST_DOMAIN_RADIUS, (float) ghostDomainRadius);
        char processedTerrorLevel = Character.toUpperCase(terrorLevel);
        if (processedTerrorLevel < 'A' || processedTerrorLevel > 'S' || (processedTerrorLevel > 'D' && processedTerrorLevel < 'S')) {
            processedTerrorLevel = 'C'; // 非法等级默认C级
        }
        this.terrorLevel = processedTerrorLevel;
    }
    protected void initGoals() {
        super.initGoals();

        this.goalSelector.add(1, new MeleeAttackGoal(this, 1.2D, false));
        this.goalSelector.add(2, new CustomWanderGoal(this, 1.0D));

        // 使用正确的类名 ActiveTargetGoal
        this.targetSelector.add(1, new ActiveTargetGoal<>(this, PlayerEntity.class, 10, true, false,
                new Predicate<LivingEntity>() {
                    @Override
                    public boolean test(LivingEntity entity) {
                        if (entity instanceof PlayerEntity player) {
                            return WhiteGhostCandleItem.isHoldingWhiteCandle(player);
                        }
                        return false;
                    }
                }
        ));
    }

    // 自定义游走目标：被压制或死机时停止游走
    static class CustomWanderGoal extends WanderAroundFarGoal {
        private final GhostEntity ghost;

        public CustomWanderGoal(GhostEntity ghost, double speed) {
            super(ghost, speed);
            this.ghost = ghost;
        }

        @Override
        public boolean shouldContinue() {
            // 被压制或死机时停止游走
            return !ghost.isSuppressed() && !ghost.isDeadlocked() && super.shouldContinue();
        }
    }

    private float getRecoveryFactorByTerrorLevel(char level) {
        return switch (Character.toUpperCase(level)) {
            case 'S' -> 0.8f;
            case 'A' -> 0.6f;
            case 'B' -> 0.4f;
            default -> 0.2f;
        };
    }

    protected void initDataTracker() {
        super.initDataTracker();
        this.dataTracker.startTracking(DEADLOCKED, false);
        this.dataTracker.startTracking(GHOST_DOMAIN_RADIUS, 0.0f);
        this.dataTracker.startTracking(SPIRITUAL_STRENGTH, MAX_SPIRITUAL_STRENGTH);
        this.dataTracker.startTracking(SPIRITUAL_RESISTANCE, 50);
        this.dataTracker.startTracking(SPIRITUAL_DAMAGE, 100);
        this.dataTracker.startTracking(RECOVERY_FACTOR, getRecoveryFactorByTerrorLevel(this.terrorLevel));
    }

    @Override
    public void onTrackedDataSet(TrackedData<?> data) {
        super.onTrackedDataSet(data);
        if (data == DEADLOCKED) {
            if (this.isDeadlocked()) {
                clearGhostDomainEffects();
            }
        }
    }

    // 1. 实现 getMainArm()（新增方法）
    @Override
    public Arm getMainArm() {
        return Arm.RIGHT; // 默认使用右手为主手
    }

    // 2. 无法被伤害
    @Override
    public boolean damage(DamageSource source, float amount) {
        // 处理灵异伤害类型
        if (source.isOf(ModDamageSources.GHOST)) {
            int resistance = getSpiritualResistance();
            int damageToStrength = (int)amount - resistance;
            damageToStrength = (amount > 0 && damageToStrength <= 0) ? 1 : Math.max(0, damageToStrength);
            if (damageToStrength > 0) {
                setSpiritualStrength(Math.max(0, getSpiritualStrength() - damageToStrength));
            }
            return false; // 不扣除生命值
        }
        // 其他伤害类型不影响生命值
        return false;
    }

    // 3. 装备相关方法
    @Override
    public void equipStack(EquipmentSlot slot, ItemStack stack) {
        // 幽灵不装备任何物品
    }

    @Override
    public ItemStack getEquippedStack(EquipmentSlot slot) {
        return ItemStack.EMPTY;
    }

    @Override
    public void tick() {
        super.tick();
        // 被压制或死机时停止移动
        if (isSuppressed() || isDeadlocked() || movementDisabled) {
            this.setVelocity(Vec3d.ZERO);
            return;
        }
        // 每 tick 都检查目标条件
        if (this.getTarget() instanceof PlayerEntity player) {
            if (!WhiteGhostCandleItem.isHoldingWhiteCandle(player)) {
                this.setTarget(null); // 清除目标
            }
        }

        // 灵异强度恢复逻辑
        // 被棺材钉压制时不进行复苏
        if (!isDeadlocked() && !hasCoffinNail() && getSpiritualStrength() < MAX_SPIRITUAL_STRENGTH) {
            if (this.getWorld().getTime() % 20 == 0) { // 每秒恢复一次
                int recovery = (int)(getRecoveryFactor() * 10);
                setSpiritualStrength(getSpiritualStrength() + recovery);
            }
        }

        // 可见性计时器逻辑
        if (visibleTicks > 0) {
            visibleTicks--;
            if (visibleTicks == 0) {
                isVisible = false;
            }
        }

        // 检查死机状态阈值
        if (getSpiritualStrength() < MIN_STRENGTH_FOR_DEADLOCK && !isDeadlocked()) {
            setDeadlocked(true);
        }
        // 4. 黑色粒子特效
        if (ENABLE_INVULNERABLE && ENABLE_BLACK_PARTICLES && this.getWorld().isClient && getVisible()) {
            Vec3d pos = this.getPos();
            for (int i = 0; i < 5; i++) {
                double offsetX = random.nextGaussian() * 0.5;
                double offsetY = random.nextGaussian() * 0.5;
                double offsetZ = random.nextGaussian() * 0.5;
                this.getWorld().addParticle(ParticleTypes.SMOKE,
                        pos.x + offsetX, pos.y + offsetY, pos.z + offsetZ, 0, 0, 0);
            }
        }

        // 5.基础鬼域逻辑
        if (!isDeadlocked() && ghostDomainEnabled && hasGhostDomain) {
            double radius = getGhostDomainRadius();
            // 修复getPlayers方法调用和距离计算
            List<PlayerEntity> nearbyPlayers = this.getWorld().getPlayers().stream()
                    .filter(player -> {
                        double dx = player.getX() - this.getX();
                        double dy = player.getY() - this.getY();
                        double dz = player.getZ() - this.getZ();
                        double distanceSq = dx * dx + dy * dy + dz * dz;
                        return distanceSq <= radius * radius;
                    })
                    .collect(Collectors.toList());
            for (PlayerEntity player : nearbyPlayers) {
                // 检查玩家鬼域等级是否高于当前鬼的鬼域等级
                boolean isImmune = GhostDomainManager.isImmuneToGhostDomain(player, this.ghostDomainLevel);
                if (isImmune) {
                    continue;
                }
                // 施加失明效果
                if (ghostDomainLevel >= 1) {
                    applyDefaultEffects(player);
                }
                // 施加缓慢效果
                if (ghostDomainLevel >= 2) {
                    player.addStatusEffect(new StatusEffectInstance(StatusEffects.SLOWNESS, 200, 1, false, false));
                }
                // 阻止离开逻辑
                // 施加迷失效果
                if (ghostDomainLevel >= 3 && !RedGhostCandleItem.isHoldingCandle(player)) {
                    StatusEffectInstance lostEffect = new LostStatusEffectInstance(ModEffects.LOST, Integer.MAX_VALUE, 0, false, false, false, this.getUuid());
                    player.addStatusEffect(lostEffect);
                }
                // 添加4级鬼域效果
                if (ghostDomainLevel >= 4) {
                    player.addStatusEffect(new StatusEffectInstance(StatusEffects.POISON, 200, 0, false, false));
                }
                // 新增杀人规则判断与执行
                if (killingRulesEnabled && shouldAttackPlayer(player) && !RedGhostCandleItem.isHoldingCandle(player)) {
                    executeAttack(player);
                }

            }
        }
    }

    @Override
    public Iterable<ItemStack> getArmorItems() {
        return Collections.emptyList();
    }

    @Override
    public ItemStack getStackInHand(Hand hand) {
        return ItemStack.EMPTY;
    }

    /**
     * 获取鬼域半径
     * @return 鬼域半径
     */
    public int getSpiritualStrength() { return this.dataTracker.get(SPIRITUAL_STRENGTH); }
    public int getSpiritualResistance() { return this.dataTracker.get(SPIRITUAL_RESISTANCE); }
    public int getSpiritualDamage() { return this.dataTracker.get(SPIRITUAL_DAMAGE); }
    public float getRecoveryFactor() { return this.dataTracker.get(RECOVERY_FACTOR); }

    public void setSpiritualStrength(int strength) {
        this.dataTracker.set(SPIRITUAL_STRENGTH, Math.max(0, strength));
    }

    public float getGhostDomainRadius() {
        return this.dataTracker.get(GHOST_DOMAIN_RADIUS);
    }

    public void setGhostDomainRadius(float radius) {
        this.dataTracker.set(GHOST_DOMAIN_RADIUS, radius);
    }

    /**
     * 获取恐怖等级
     * @return 恐怖等级 (S/A/B/C/D)
     */
    public char getTerrorLevel() {
        return terrorLevel;
    }

    /**
     * 获取随机数生成器实例
     * @return 随机数生成器
     */
    protected Random getGhostRandom() {
        return random;
    }

    public LivingEntity getAttackTarget() {
        return attackTarget;
    }

    /**
     * 攻击时设置可见状态并持续3秒
     */
    public void setVisibleOnAttack() {
        this.isVisible = true;
        this.visibleTicks = 60; // 3秒 = 60ticks
    }

    public boolean isVisible() {
        return isVisible;
    }

    protected boolean shouldAttackPlayer(PlayerEntity player) {
        return false;
    }

    protected void executeAttack(PlayerEntity player) {
        // 默认攻击实现
    }
}